package com.tina.netty;

import com.alibaba.fastjson.JSONObject;
import com.tina.service.ChatService;
import com.tina.utils.JsonUtils;
import com.tina.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import io.netty.channel.ChannelHandler.Sharable;

/**
 * 用于处理消息的handler
 * 由于它的传输数据的载体是frame，这个frame 在netty中，是用于为websocket专门处理文本对象的，frame是消息的载体，此类叫：TextWebSocketFrame
 *
 * @author tina
 */
@Slf4j
@Component
@Sharable
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //获取客户端所传输的消息
        String content = msg.text();
        log.info("content->{}", content);
        //1.获取客户端发来的消息
        DataContent dataContent = JsonUtils.jsonToPojo(content, DataContent.class);
        String getType = dataContent.getType();
        ChatService chatService = SpringUtil.getBean(ChatService.class);
        switch (getType) {
            case "REGISTER":
                // 第一次连接
                log.info("getMemberId->{}", dataContent.getMemberId());
                chatService.register(dataContent.getMemberId(), ctx);
                break;
            case "SINGLE_SENDING":
                // 单聊
                chatService.singleSend(dataContent.getChatMsg());
                break;
            case "CHAT_LOG":
                // 查询聊天记录、 然后修改未读取消息
                chatService.selectChatMsgSend(dataContent.getChatMsg(), ctx);
                break;
            case "HEARTBEAT":
                // 接收心跳MY_FRIEND
                log.info("接收来自：{} 的心跳", dataContent.getMemberId());
                break;
            default:

                break;
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("新连接进来。{}", ctx.channel().id().asShortText());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("连接成功"));
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        String chanelId = ctx.channel().id().asShortText();
        System.out.println("客户端被移除：channel id 为：" + chanelId);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        //发生了异常后关闭连接，同时从channelgroup移除
        ctx.channel().close();

    }
}
